//
//  QJHttpRequest.m
//  QJWork
//
//  Created by 高中雷 on 15/5/30.
//  Copyright (c) 2015年 高中雷. All rights reserved.
//

#import "QJHttpRequest.h"

@implementation QJHttpRequest

NSURL *finalUrl = nil;

+(QJHttpRequest*)http{
    static QJHttpRequest * http = NULL;
    
    if (!http) {
        http = [[[self class] alloc] init];
        
    }
    return http;
}

- (id)init {
    self = [super init];
    if (self) {
       
        
    }
    return self;
}

- (void)operationManager{
    _manager = [AFHTTPRequestOperationManager manager];
    _manager.operationQueue.maxConcurrentOperationCount = 3;
}

-(void)header:(NSDictionary*)header{
    //头参数
    _manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [_manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    for(NSString *key in header.allKeys){
        [_manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
    }
}

- (AFHTTPRequestOperation *)requestWithURL:(NSString *)url
                             requestHeader:(NSDictionary *)header
                                    params:(NSMutableDictionary *)params
                                    image:(NSArray *)imageArray
                                httpMethod:(NSString *)httpMethod
                                   success:(successBlock)successHandler
                                   failure:(failureBlock)failureHandler
{
    [self operationManager];
    [self header:header];
    NSLog(@"url>>>>>> %@ \n  %@",url,params);
    if([httpMethod isEqualToString:@"GET"]||[httpMethod isEqualToString:@"get"]){
        return [self get:url params:params success:successHandler failure:failureHandler];
    }else if([httpMethod isEqualToString:@"POST"]||[httpMethod isEqualToString:@"post"]){
        return [self post:url params:params success:successHandler failure:failureHandler];
    }else if([httpMethod isEqualToString:@"POSTIMAGE"]||[httpMethod isEqualToString:@"postimage"]){
        return [self postImage:url params:params imageArray:imageArray success:successHandler failure:failureHandler];
    }else if([httpMethod isEqualToString:@"POSTDATA"]||[httpMethod isEqualToString:@"postdata"]){
        return [self postData:url params:params success:successHandler failure:failureHandler];
    }
    return nil;
}





- (AFHTTPRequestOperation *)get:(NSString *)url params:(NSDictionary *)params  success:(successBlock)successHandler failure:(failureBlock)failureHandler
{
    // 1.获得请求管理者
    // 2.发送GET请求
    // 3.解析数据
    
   return  [_manager GET:url parameters:params
     success:^(AFHTTPRequestOperation *operation, id responseObj) {
         
         finalUrl = operation.request.URL;
         
         if (successHandler) {
            
             successHandler(responseObj);
             
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         
         NSLog(@"get网络请求失败：%@", error);
         
         finalUrl = operation.request.URL;
         NSLog(@"finalUrl: %@", finalUrl);
         
         if (failureHandler) {
             failureHandler(error);
         }
     }];
}

- (AFHTTPRequestOperation *)post:(NSString *)url params:(id)params success:(failureBlock)successHandler failure:(failureBlock)failureHandler
{
    // 1.获得请求管理者
    // 2.发送POST请求
    // 3.解析数据

    
    NSDate *date = [NSDate date];
   return  [_manager POST:url parameters:params
           success:^(AFHTTPRequestOperation *operation, id responseObj) {
               if (successHandler) {
                    NSLog(@"返回接口。。。。%f",[date timeIntervalSinceNow]);
                   successHandler(responseObj);
               }
           } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
               
               // 答应错误 并且给子类
               NSLog(@"post网络请求失败：%@", error);
               
               finalUrl = operation.request.URL;
               // YKLog(@"finalUrl: %@", finalUrl);
               if (failureHandler) {
                   failureHandler(error);
               }
           }];
    
   
}

//请求加图片

- (AFHTTPRequestOperation *)postImage:(NSString *)url params:(id)params imageArray:(NSArray *)imageArray success:(failureBlock)successHandler failure:(failureBlock)failureHandler
{
    // 1.获得请求管理者
    
    // 2.发送POST请求
    // 3.解析数据
    
    return [_manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        for(int i = 0 ; i<imageArray.count; i++){

            NSData *data = (NSData *)imageArray[i];
            [formData appendPartWithFileData:data name:@"img" fileName:@"picfile.jpg" mimeType:@"jpg/png"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (successHandler) {
            successHandler(responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 答应错误 并且给子类
        NSLog(@"post网络请求失败：%@", error);
        
        finalUrl = operation.request.URL;
        // YKLog(@"finalUrl: %@", finalUrl);
        if (failureHandler) {
            failureHandler(error);
        }

    }];
    
}

- (AFHTTPRequestOperation *)postData:(NSString *)url params:(id)params success:(successBlock)successHandler failure:(failureBlock)failureHandler
{
    [self operationManager];
    _manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [_manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    NSMutableURLRequest *request =
    [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    if(params){
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error: nil];
        NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
        [request setHTTPBody:tempJsonData];
    }
     [request setHTTPMethod:@"POST"];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (successHandler) {
            successHandler(responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failureHandler) {
            failureHandler(error);
        }
    }];
    
    [operation start];
    
    return operation;
    
}


@end
